package com.ai.sevice;

import com.ai.aspect.CacheService;
import com.ai.dao.entity.ai.AiDynamic;
import com.ai.repository.ai.AiDynamicRepository;
import com.ai.sevice.abc.*;
import com.ai.sevice.ai.GptService;
import com.ai.sevice.ai.remote.CompletionsResponse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.math.BigDecimal;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AbcService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private AiDynamicRepository aiDynamicRepository;
    @Autowired
    private GptService gptService;

    @CacheService()
    public List<ZuoweninfoDataParagraph> getCache1(ZuoweninfoDataParagraph request,String x,Integer y,boolean bo) {

        return null;
    }

    @CacheService()
    public List<ZuowenpaperDataListRecommend> getCache2(String value) {

        return null;
    }

    public void getProgrammerAnswer() {
        List<String> questionList = new ArrayList<>();
        //questionList.add("给定一个整数数组nums和一个整数目标值target，请你在该数组中找出和为目标值target的那两个整数，并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是，数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。");
//        questionList.add("给定一个字符串s，请你找出其中不含有重复字符的最长子串的长度。");
//        questionList.add("给定两个大小分别为m和n的正序（从小到大）数组nums1和nums2。请你找出并返回这两个正序数组的中位数。算法的时间复杂度应该为O(log(m+n))");
//        questionList.add("给你一个整数x，如果x是一个回文整数，返回true ；否则，返回false。回文数是指正序（从左向右）和倒序（从右向左）读都是一样的整数。例如：121是回文，而123不是。");
//        questionList.add("给你一个整数数组nums，判断是否存在三元组[nums[i],nums[j],nums[k]]满足 i != j、i != k 且 j != k ，同时还满足nums[i] + nums[j] + nums[k] == 0。请你返回所有和为0且不重复的三元组。注意：答案中不可以包含重复的三元组。");
//        questionList.add("给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数，使它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在恰好一个解。");
//        questionList.add("给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。");
//        questionList.add("数字 n 代表生成括号的对数，请你设计一个函数，用于能够生成所有可能的并且 有效的 括号组合。");
//        questionList.add("给你一个链表数组，每个链表都已经按升序排列。请你将所有链表合并到一个升序链表中，返回合并后的链表。");
//        questionList.add("给你两个字符串 haystack 和 needle ，请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标（下标从 0 开始）。如果 needle 不是 haystack 的一部分，则返回-1 。");
//        questionList.add("给定一个字符串s和一个字符串数组words。words中所有字符串长度相同。s中的串联子串是指一个包含words中所有字符串以任意顺序排列连接起来的子串。例如，如果words = [\"ab\",\"cd\",\"ef\"]，那么\"abcdef\"，\"abefcd\"，\"cdabef\"，\"cdefab\"，\"efabcd\"，和\"efcdab\"都是串联子串。\"acdbef\"不是串联子串，因为他不是任何words排列的连接。返回所有串联字串在s中的开始索引。你可以以任意顺序返回答案。");
        log.info("getProgrammerAnswer开始");
        for (String question : questionList){
            try {
                question = "生成程序代码：用java写：" + question;
                AiDynamic aiDynamic = new AiDynamic();
                CompletionsResponse completionsResponse = gptService.getCompletionsResponse(question);
                String content = completionsResponse.getChoices().get(0).getMessage().getContent();
                aiDynamic.setIsDelete(2);
                aiDynamic.setOptionType("programmer");
                aiDynamic.setSource("gpt");
                aiDynamic.setTitle(question.replace("生成程序代码：",""));
                //aiDynamic.setSummary("java");
                aiDynamic.setContent(content);
                //aiDynamicRepository.insertSelective(aiDynamic);
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        }
        log.info("getProgrammerAnswer结束");
    }

    public void getFullScore() {
        try {
            List<Integer> yearList = Arrays.asList(2022,2021,2020,2019,2018,2017,2016,2015);
//            List<Integer> yearList = Arrays.asList(2019);
            List<AiDynamic> aiDynamicList = new ArrayList<>();
            for (Integer year : yearList) {
                String url = "https://easylearn.baidu.com/edu-web/gaokao/zuowenpaperlist?showComposition=1&year=" + year;
                ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
                HttpHeaders responseHeaders = forEntity.getHeaders();
                List<String> cookies = responseHeaders.get("Set-Cookie");
                String body = forEntity.getBody();
                Zuowenpaper zuowenpaper = JSON.parseObject(body, Zuowenpaper.class);
                for (ZuowenpaperDataList list : zuowenpaper.getData().getList()) {
                    String paperType = list.getPaperType();
                    List<ZuowenpaperDataListRecommend> recommendList = list.getRecommend();
                    for (ZuowenpaperDataListRecommend recommend : recommendList) {
                        String xqUrl = null;
                        try {
                            String id = recommend.getId();
                            String title = recommend.getTitle();
                            String text = recommend.getText();
                            AiDynamic aiDynamic = new AiDynamic();
                            aiDynamic.setIsDelete(2);
                            aiDynamic.setOptionType("composition");
                            aiDynamic.setSource("baidu");
                            aiDynamic.setTitle(title);
                            aiDynamic.setSummary(text);
                            HttpHeaders headers = new HttpHeaders();
                            HttpEntity<String> entity = new HttpEntity<>("", headers);
                            xqUrl = "https://easylearn.baidu.com/edu-web/gaokao/zuoweninfo?id=" + id + "&paper=" + paperType + "&year=" + year;
                            xqUrl = URLDecoder.decode(xqUrl, "UTF-8");
                            ResponseEntity<String> xqForEntity = restTemplate.exchange(xqUrl, HttpMethod.GET, entity, String.class);
                            Zuoweninfo zuoweninfo = JSON.parseObject(xqForEntity.getBody(), Zuoweninfo.class);
                            //String xqTitle = zuoweninfo.getData().getTitle();
                            StringBuilder content = new StringBuilder();
                            List<ZuoweninfoDataParagraph> paragraphList = zuoweninfo.getData().getParagraph();
                            for (ZuoweninfoDataParagraph paragraph : paragraphList) {
                                content.append("    ").append(paragraph.getText()).append("\r\n");
                            }
                            aiDynamic.setContent(content.toString());
                            aiDynamicList.add(aiDynamic);
                        }catch (Exception e){
                            System.out.println("异常链接：" + xqUrl);
                            //log.error(e.getMessage(),e);
                        }
                    }
                }
            }
            for(AiDynamic aiDynamic : aiDynamicList){
                //aiDynamicRepository.insertSelective(aiDynamic);
            }
            System.out.println();
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public void stressTesting() {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                Thread thread = new Thread(() -> {
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    headers.set("uid", "mmc4ngs0");

                    String requestBody = "{\"module\":\"aiAssembly\", \"key\":\"composition\"}";

                    HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

                    ResponseEntity<String> responseEntity = restTemplate.exchange(
                            "https://www.epochai.top/ai/config/get",
                            HttpMethod.POST,
                            requestEntity,
                            String.class);
                    System.out.println("mmc4ngs0 -> " + responseEntity.getBody());
                });
                thread.start();
                try {
                    TimeUnit.MILLISECONDS.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                Thread thread = new Thread(() -> {
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    headers.set("uid", "e6hj2gm0");

                    String requestBody = "{\"module\":\"aiAssembly\", \"key\":\"composition\"}";

                    HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

                    ResponseEntity<String> responseEntity = restTemplate.exchange(
                            "https://www.epochai.top/ai/config/get",
                            HttpMethod.POST,
                            requestEntity,
                            String.class);
                    System.out.println("e6hj2gm0 -> " + responseEntity.getBody());
                });
                thread.start();
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread2.start();
    }

    @Async
    public void async() {
        log.info("async start");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            log.error(e.getMessage(),e);
        }
        log.info("async end");
    }

    public String upload(MultipartFile file, String path,String password) {
        try {
            if (StringUtils.isBlank(password)){
                return "请输入密码";
            }
            if (!"123456".equals(password)){
                return "密码不正确";
            }
            //指定上传文件路径
            String filepath = "/usr/local/metal/";
//            String filepath = "D:/upload/";
            if (StringUtils.isNotBlank(path)){
                //filepath = filepath + path + File.separator;
                filepath = path;
            }
            //获取文件名
            String fileName = file.getOriginalFilename();
            File dateDir = new File(filepath);
            if (!dateDir.exists()) {
                dateDir.mkdirs();
            }
            File uploadFile = new File(filepath + fileName);
            //上传文件
            file.transferTo(uploadFile);
            return "文件上传成功";
        }catch (Exception e){
            log.error("上传文件失败",e);
        }
        return "文件上传失败";
    }

    /**
     * 股票测试
     */
    public void stock1() {

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer token");
        HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange("https://xueqiu.com", HttpMethod.GET, entity, String.class);
        HttpHeaders responseHeaders = response.getHeaders();
        List<String> cookies = responseHeaders.get("Set-Cookie");
        System.out.println(cookies);

        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        for (String cookie : cookies){
            HttpCookie httpCookie = HttpCookie.parse(cookie).get(0);
            String name = httpCookie.getName();
            String value = httpCookie.getValue();
            System.out.println(name + "\t" + value);
        }

    }

    public void stock2() {

        HttpHeaders headers = new HttpHeaders();
//        headers.set("Cookie", "xq_a_token=ebd3592a6f07cb960b9cb980e00fbb4dce12da70; xqat=ebd3592a6f07cb960b9cb980e00fbb4dce12da70; xq_r_token=f8a19d1fe4aeeb1605c79b4c4037ed3110905745; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTY4NjQ0MzQ1NCwiY3RtIjoxNjgzOTQ3MTYxODYxLCJjaWQiOiJkOWQwbjRBWnVwIn0.JepDPNH1m9G8hwKG1umXz8xQB_Bxb944gEqzcmy4VJg5QAPkNqFqXjK4N41w3EH8RtDOiyW7t2Q8kVDB2sClpOYPcUxjaijCsifEY4YqLwO0wjmJEghUzxSm9Je_w58oznUEWQUrzojPEW3u1xhkRNUkp4M9cpsjdIRUXoGQCnxGrgwVi30GNjjH-cxobkIOExzF0GFisLwdSLLmN65-Yah1OP26SYTo5OK_n-vp2wZfk3x00B4x19_OG_7vpDo_4jtmFpMFU3GbLXA2v9q10EKhltqQHnkQ1Rt94OQe3lLjS_Za4iQgL6DwAVLls7Uu68O-IGIj2JioxC1Xt_lkbw; u=401683947210073; Hm_lvt_1db88642e346389874251b5a1eded6e3=1683947211; device_id=58e7e80e76ff14be873c47e9c28e663a; s=c611s1skma; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1683947982");
        String cookie = getXueQiuCookie();
        headers.set("Cookie", cookie);
        HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange("https://stock.xueqiu.com/v5/stock/screener/quote/list.json?type=sha&order_by=percent&order=desc&size=10&page=1", HttpMethod.GET, entity, String.class);
        System.out.println(response.getBody());
    }


    private String getXueQiuCookie(){
        StringBuilder sb = new StringBuilder();
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<>("", headers);
        ResponseEntity<String> response = restTemplate.exchange("https://xueqiu.com", HttpMethod.GET, entity, String.class);
        HttpHeaders responseHeaders = response.getHeaders();
        List<String> cookies = responseHeaders.get("Set-Cookie");
        //System.out.println(cookies);
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        for (String cookie : cookies){
            HttpCookie httpCookie = HttpCookie.parse(cookie).get(0);
            String name = httpCookie.getName();
            String value = httpCookie.getValue();
            if ("xq_a_token".equals(name)){
                sb.append("xq_a_token=").append(value).append("; ");
                sb.append("xqat=").append(value).append("; ");
            } else if ("xq_r_token".equals(name)){
                sb.append("xq_r_token=").append(value).append("; ");
            } else if ("xq_id_token".equals(name)){
                sb.append("xq_id_token=").append(value).append("; ");
            } else if ("u".equals(name)){
                sb.append("u=").append(value).append("; ");
            }
        }
        long timestamp = System.currentTimeMillis() / 1000;
        sb.append("Hm_lvt_1db88642e346389874251b5a1eded6e3=").append(timestamp).append("; ");
        sb.append("device_id=").append("58e7e80e76ff14be873c47e9c28e663a").append("; ");
        sb.append("s=").append("58e7e80e76ff14be873c47e9c28e663a").append("; ");
        sb.append("Hm_lpvt_1db88642e346389874251b5a1eded6e3=").append(timestamp+8047).append("; ");
        //sb.append("acw_tc=").append("2760779516839570583682601efeb40efb6724ff56ed270fc0d8868dae5650").append("; ");
        System.out.println(sb.toString());
        return sb.toString();
    }
}
